import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation } from "react-router-dom";
import { Tabs } from "antd-mobile";
import { createAction } from "@common/utils";
import ItemDetails from "./ItemDetails";
import BarcodeDetails from "./BarcodeDetails";
import {
  SAGA_TMP_PALLET_LOAD_ITEM_DETAILS,
  SAGA_TMP_PALLET_LOAD_BARCODE_DETAILS,
} from "@store/tmp-pallet/saga-types";
import { SET_TMP_PALLET_DATA_ID } from "@store/tmp-pallet/action-types";
import { SET_SHOW_HOME_BTN } from "@store/global-state/action-types";

const Details = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const itemDetails = useSelector((state) => state.tmpPallet.itemDetails);
  const barcodeDetails = useSelector((state) => state.tmpPallet.barcodeDetails);

  const getItemDetails = () => {
    let id = searchParams.get("id");
    dispatch(
      createAction(SAGA_TMP_PALLET_LOAD_ITEM_DETAILS, { tmpPalletDataId: id })
    );
  };

  useEffect(() => {
    getItemDetails();
    dispatch(createAction(SET_SHOW_HOME_BTN, false));
    return () => {
      dispatch(
        createAction(SET_TMP_PALLET_DATA_ID, { id: searchParams.get("id") })
      );
      dispatch(createAction(SET_SHOW_HOME_BTN, true));
    };
  }, []);

  const getBarcodeDetails = () => {
    let id = searchParams.get("id");
    dispatch(
      createAction(SAGA_TMP_PALLET_LOAD_BARCODE_DETAILS, {
        tmpPalletDataId: id,
      })
    );
  };

  const handleChange = (activeKey) => {
    if (activeKey === "items") {
      getItemDetails();
    } else {
      getBarcodeDetails();
    }
  };

  return (
    <div style={{ marginTop: "45px", backgroundColor: "white" }}>
      <Tabs
        style={{ "--content-padding": "0" }}
        defaultActiveKey="items"
        onChange={handleChange}
      >
        <Tabs.Tab title="物料明细" key="items">
          <ItemDetails items={itemDetails} />
        </Tabs.Tab>
        <Tabs.Tab title="条码明细" key="barcodes">
          <BarcodeDetails items={barcodeDetails} isMix={false} />
        </Tabs.Tab>
      </Tabs>
    </div>
  );
};

export default Details;
